function t = randomSinusWalk(x,f,s,seed)
% Returns a consinus function, where the frequency has been added a
% gaussina random walk such that
%
% t(n) = real(exp(i*2*pi*(x + e(n)/f))
% e(n) = randn(1)*s + e(n-1)
%
% t = randomSinusWalk(x,f,s)
%
% x         Time.
% f         Frequency
% s         Variance of the random walk.
% seed      Seed for the random number generator.
%
% t    = real(exp(i*2*i(x + e(n)/f)))
% e(n) = e(n-1) + randn*s

persistent x0 r n tlast

fr = 1;

if nargin < 3; s = 1; end
if nargin > 3 && isempty(r);
    randn('state',seed);
    r = seed;
end

if isempty(x0)
    x0 = 0;
    n = 0;
    fprintf(1,'Downsample set to: %u\n',fr);
end

if numel(x) == 1
    x0 = x0 + s*randn(1);
    if mod(n,fr)
        t = tlast;        
    else
        t = real(exp(1i*2*pi*(x + x0/f)));
        tlast = t;
    end
    n = n+1;
else
    x0 = randn(size(x));
    x0 = cumsum(x0);
    t = real(exp(1i*2*pi*(x + (s*x0)/f)));
    t(:) = t((1:numel(x))-mod(0:numel(x)-1,fr)); % Downsample
end
end